import prisma from '@/server/database/client'
// import {Prisma} from '@prisma/client'
import dayjs from 'dayjs'

export async function getItemBalance(param:ItemListDateParam,user_id:string){
  const {happened_after,happened_before} = param
  const expensesItems = await prisma.item.aggregate({
    _sum:{
      amount:true
    },
    where:{
      kind:'expenses',
      user_id,
      happen_at: {
        gte: new Date(happened_after),
        lte: new Date(happened_before), 
      },
      deleted_at: null
   },
  })
  const incomeItems = await prisma.item.aggregate({
    _sum:{
      amount:true
    },
    where:{
      kind:'income',
      happen_at: {
        gte: new Date(happened_after),
        lte: new Date(happened_before), 
      },
      deleted_at: null
   },
  })
  const expenses = expensesItems._sum.amount || 0
  const income = incomeItems._sum.amount || 0
  return {expenses, income, balance: income - expenses}
}

export async function createItem(data:Omit<Item, "id"|"tag">){
  const item = await prisma.item.create({ data })
  return item
}

// export async function updateItem(data:Omit<Item, "tag">){
//   const item = await prisma.item.update({ where: { id: data.id }, data })
//   return item
// }
// export async function deleteItem(id:number){
//   const item = await prisma.item.delete({ where:{id} })
//   return item
// }
// export async function findItemById(id:number){
//   const item = await prisma.item.findUnique({ where:{id} })
//   return item
// }
export async function findItemsByUserId(user_id:string,page:number,happened_after:string,happened_before:string){
  const per_page = 25
  const count = await prisma.item.count({
    where: {
      user_id,
      happen_at: {
        gte: new Date(happened_after), // 将字符串日期转换为 Date 对象
        lte: new Date(happened_before),   // 将字符串日期转换为 Date 对象
      },
      deleted_at: null
    },
  })
  const items = await prisma.item.findMany({
    where:{
      user_id,
      happen_at: {
        gte: new Date(happened_after), // 将字符串日期转换为 Date 对象
        lte: new Date(happened_before),   // 将字符串日期转换为 Date 对象
      },
      deleted_at: null
    },
    include: {
      tag: true, // 使用 include 来获取与 Item 关联的 Tag
    },
    skip: (page-1)*per_page,
    take: per_page,
  })
  return {
    resources:items,
    pager:{
      page,
      per_page,
      count
    }
  }
}

type TagGroupByData = Tag & {tag_id:number, total_amount: number}
type HappenAtCountItem = {
  happen_at: Date,
  _sum: {
    amount: number
  }
}
// group_by: Prisma.ItemScalarFieldEnum
export type GroupByType = 'tag_id' | 'happen_at'
export async function getItemsSummary(happened_after:string,happened_before:string,group_by: GroupByType, kind:TagType,user_id:string){
  let groups
  if(group_by==='tag_id'){
    const count = await prisma.$queryRaw`
      SELECT
        I.tag_id,
        SUM(I.amount) AS total_amount,
        T.*
      FROM 
        Item AS I
      JOIN
        Tag AS T ON I.tag_id = T.id
      WHERE
        I.happen_at >= ${happened_after}
        AND I.happen_at <= ${happened_before}
        AND I.kind = ${kind}
        AND I.user_id = ${user_id}
        AND I.deleted_at IS NULL
      GROUP BY
        I.tag_id
    `
    groups = (count as TagGroupByData[]).map(ele=>{
      const {tag_id, total_amount:amount, ...tag} = ele
      return {
        tag_id, tag, amount:+amount
      }
    })
  }else if(group_by === 'happen_at'){
    const count = await prisma.item.groupBy({
      by:[group_by],
      where: {
        kind,
        user_id,
        happen_at: {
          gte: new Date(happened_after), // 将字符串日期转换为 Date 对象
          lte: new Date(happened_before),   // 将字符串日期转换为 Date 对象
        },
        deleted_at: null
      },
      _sum: {
        amount: true,
      }
    })
    // console.log(count,'🐳🐗')
    // groups = count.map((ele)=>{
    groups = (count as HappenAtCountItem[]).map((ele)=>{
      const {happen_at,_sum:{amount}} = ele
      return {happen_at:dayjs(happen_at).format('YYYY-MM-DD'),amount}
    })
  }
  return {groups}
}

export async function deleteItemsByTagId(tag_id:number){
  const currentDate = new Date()
  const items =await prisma.item.updateMany({
    where: {
      tag_id: tag_id,
    },
    data: {
      deleted_at: currentDate,
    },
  })
  return items.count
}

export async function deleteItemById(id:number){
  const currentDate = new Date()
  const tag = await prisma.item.update({ 
    where: { id },
    data: {
      deleted_at: currentDate,
    }
  })
  return tag
}